<script lang="ts" setup>
import { ref } from 'vue'
import Upload from '@/components/upload.vue'
import UploadJson from '@/components/uploadJson.vue'
import http from '@/http'
import { ElMessage, ElMessageBox } from 'element-plus'
import copy from 'copy-to-clipboard'
import Utility from '@/utils'
const ruleFormRef = ref(null)
const loading = ref(false)
const ruleForm = ref({
  zhDataSource: '',
  enDataSource: '',
  replaceTemplate: '',
  sheetName: '',
})
const rules = ref({
  zhDataSource: [
    { required: true, message: '上传中文数据源', trigger: 'blur' },
  ],
  enDataSource: [
    { required: true, message: '上传英文数据源', trigger: 'blur' },
  ],
  replaceTemplate: [
    { required: true, message: '上传中英文替换模版', trigger: 'blur' },
  ],
  sheetName: [
    { required: true, message: '请输入替换指定表名', trigger: 'blur' },
  ],
})
function submitTempalte(formEl) {
  formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true
      http
        .post({
          url: '/upload/national_template',
          data: {
            fileUrl: ruleForm.value.replaceTemplate,
            sheetName: ruleForm.value.sheetName,
          },
        })
        .then((result) => {
          getReplaceJson(
            JSON.parse(ruleForm.value.zhDataSource),
            JSON.parse(ruleForm.value.enDataSource),
            result.xlsxContent.map((v) => ({
              ...v,
              'zh-CN': v['zh-CN'].trim(),
            }))
          )
        })
        .finally(() => {
          loading.value = false
        })
    }
  })
}
function handleReplaceText(matchSource, enSource) {
  const replaceList = []
  for (const matchItem of matchSource) {
    if (enSource[matchItem.key] !== matchItem.en) {
      replaceList.push({
        key: matchItem.key,
        originEn: enSource[matchItem.key],
        replaceEn: matchItem.en,
      })
      enSource[matchItem.key] = matchItem.en
    }
  }
  ElMessageBox.confirm(
    `替换成功，一共替换了${replaceList.length}条数据`,
    '替换成功！',
    {
      confirmButtonText: '一键复制替换后的英文数据',
      cancelButtonText: '取消',
      type: 'success',
    }
  ).then(() => {
    copyToClipboard(JSON.stringify(enSource))
  })
  console.log(replaceList, 'replaceList')
  return enSource
}
const copyToClipboard = (data) => {
  copy(data)
  ElMessage.success('复制成功！')
}
function getReplaceJson(zhSource, enSource, xlsxCon) {
  const matchingLinkSource = getMatchingLink(zhSource, xlsxCon)

  if (matchingLinkSource.length) {
    return JSON.stringify(handleReplaceText(matchingLinkSource, enSource))
  } else {
    ElMessage({
      message: '未找到表中数据英文匹配的中文',
      type: 'error',
    })
  }
}
// 中文数据和xlsx数据关联
function getMatchingLink(zhSource, xlsxCon) {
  const matchingLink = [] //跟表中有关联的数据
  for (const item of xlsxCon) {
    for (const key in zhSource) {
      if (item['zh-CN'] === zhSource[key] + ',') {
        matchingLink.push({
          key,
          zh: zhSource[key],
          en: item['en'],
        })
      }
    }
  }
  return matchingLink
}
function handleAccept(type, data) {
  const ruleFormFlag = ruleForm.value
  ruleFormFlag[type] = data
  ruleForm.value = ruleFormFlag
}
function hanldeDownTem() {
  const _fileUrl = `/zh_en_replace_template.xlsx`
  Utility.downloadFile(_fileUrl, '中英文替换模版.xlsx')
}
</script>
<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm box-wapper"
    status-icon
  >
    <el-form-item label="中文数据源" prop="zhDataSource">
      <UploadJson
        @accept="(data) => handleAccept('zhDataSource', data)"
        accept=".json"
        uploadButttonName="上传中文数据源"
      />
    </el-form-item>
    <el-form-item label="英文数据源" prop="enDataSource">
      <UploadJson
        accept=".json"
        uploadButttonName="上传英文数据源"
        @accept="(data) => handleAccept('enDataSource', data)"
      />
    </el-form-item>
    <el-form-item label="中英文替换模版" prop="replaceTemplate">
      <Upload
        accept=".xlsx"
        uploadButttonName="上传中英文替换模版"
        @accept="(data) => handleAccept('replaceTemplate', data)"
      />
      <el-button
        style="margin-bottom: 10px; margin-left: 10px"
        type="primary"
        link
        @click="hanldeDownTem"
      >
        下载模版
      </el-button>
    </el-form-item>
    <el-form-item label="替换指定表名" prop="sheetName">
      <el-input v-model="ruleForm.sheetName" />
    </el-form-item>

    <el-button
      type="primary"
      @click="submitTempalte(ruleFormRef)"
      :loading="loading"
    >
      {{ loading ? '替换中，请稍后' : '开始替换' }}
    </el-button>
  </el-form>
</template>
<style lang="scss" scoped>
.box-wapper {
  padding: 20px;
}
</style>
